﻿using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;
using System.Text.RegularExpressions;

namespace Wsp365.MobileAccess.UpdateNavigationEventReceiver
{
    /// <summary>
    /// List Item Events
    /// </summary>
    public class UpdateNavigationEventReceiver : SPItemEventReceiver
    {
       /// <summary>
       /// An item is being added.
       /// </summary>
       public override void ItemAdding(SPItemEventProperties properties)
       {
           base.ItemAdding(properties);
           FixMobileNavigation(properties.Web);
       }

       /// <summary>
       /// An item is being updated.
       /// </summary>
       public override void ItemUpdating(SPItemEventProperties properties)
       {
           base.ItemUpdating(properties);
           FixMobileNavigation(properties.Web);
       }

       internal static void FixMobileNavigation(SPWeb web)
       {
           FixMobileNavigation(web,"wh_leftnavhtml");
           FixMobileNavigation(web,"wh_sitemaphtml");
           FixMobileNavigation(web, "wh_topnavhtml");
       }

       internal static void FixMobileNavigation(SPWeb web, string propertyName)
       {
           string propertyValue = web.GetProperty(propertyName) as string;
           if (!string.IsNullOrEmpty(propertyValue))
           {
               propertyValue = Regex.Replace(propertyValue, "href=\"/[^\"]*", (Match match) =>
               {
                   return match.Value.Replace("?mobile=0", "") + "?mobile=0";
               });
               web.SetProperty(propertyName, propertyValue);
               web.Update();
           }
       }


    }
}
